package com.company.project.service.impl;

import com.company.project.core.*;
import com.company.project.dao.StudentDao;
import com.company.project.dao.SysRoleAuthMapper;
import com.company.project.dao.SysRoleMapper;
import com.company.project.dao.SysUserMapper;
import com.company.project.model.Student;
import com.company.project.model.SysRole;
import com.company.project.model.SysRoleAuth;
import com.company.project.model.SysUser;
import com.company.project.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.UUID;


/**
 * Created by CodeGenerator on 2020/04/18.
 */
@Service
@Transactional
public class SysUserServiceImpl extends AbstractService<SysUser> implements SysUserService {
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private SysRoleAuthMapper sysRoleAuthMapper;
    @Resource
    private StudentDao studentDao;

    @Override
    public Result register(String userName, String phone, String email, String pwd, String userType,String idCard) {
//        用户注册
        SysUser sysUser = new SysUser();
        sysUser.setUserName(userName);
        sysUser.setPhone(phone);
        sysUser.setEmail(email);
        sysUser.setPwd(pwd);
        sysUser.setCreator(1);
        sysUser.setUpdator(1);
        sysUser.setStatus((short)1);
        sysUser.setUserType(userType);
        if (userType.equals("student")){
            if (StringUtils.isEmpty(idCard)){
                return ResultGenerator.genFailResult(ResultCode.IDCARD_ERROR);
            }
            Student studentByIdCard = studentDao.getStudentByIdCard(idCard);
            if (null == studentByIdCard){
                return ResultGenerator.genFailResult(ResultCode.IDCARD_CONFIG_ERROR);
            }
            sysUser.setIdCard(idCard);
        }

        sysUser.setSalt(UUID.randomUUID().toString());
        sysUser.setCreateTime(new Date());
        sysUser.setUpdateTime(new Date());
        int userResult = sysUserMapper.insert(sysUser);
        if (userResult == 0){
            return ResultGenerator.genFailResult();
        }
//        分配角色
        Result result = roleGenerator(sysUser.getId(), userType);
        return result;
    }

    /**
     * 分配角色
     * @param userId 用户ID
     * @param userType 用户类型
     * @return
     */
    private Result roleGenerator(int userId,String userType){
        SysRole sysRole = sysRoleMapper.selectByCode(userType);
        if (sysRole == null){
            return ResultGenerator.genFailResult(ResultCode.ROLE_CONFIG_ERROR);
        }
        SysRoleAuth sysRoleAuth = new SysRoleAuth();
        sysRoleAuth.setPartyId(userId);
//        类型为1表明是用户权限
        sysRoleAuth.setPartyType((short)1);
        sysRoleAuth.setRoleId(sysRole.getId());
        sysRoleAuth.setStatus((short)1);
        sysRoleAuth.setCreator(1);
        sysRoleAuth.setUpdator(1);
        sysRoleAuth.setCreateTime(new Date());
        sysRoleAuth.setUpdateTime(new Date());
        int roleAuthResult = sysRoleAuthMapper.insert(sysRoleAuth);
        if (roleAuthResult == 0){
            return ResultGenerator.genFailResult();
        }
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 条件查询
     *
     * @param userName    用户名
     * @param keyword     关键词
     * @param currentPage 当前页
     * @param size        每页大小
     * @return
     */
    @Override
    public Result getConditionList(String userName, String keyword, int currentPage, int size) {
        Integer count = sysUserMapper.countSysUserList(userName,keyword);
        Page page = new Page();
        page.setAllRow(count);
        page.setCurrentPage(currentPage);
        page.setSize(size);
        List<SysUser> userList = sysUserMapper.getSysUserList(userName,keyword,page.getStart(),page.getSize());
        return ResultGenerator.genSuccessResult(userList,page);
    }

    /**
     * 更新用户状态
     *
     * @param userId 用户ID
     * @param status 用户状态
     * @return
     */
    @Override
    public Result changeStatus(int userId, int status) {
        sysUserMapper.changeStatus(userId,status);
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 修改密码
     *
     * @param oldPwd 旧密码
     * @param newPwd 新密码
     * @return
     */
    @Override
    public Result changePassword(String oldPwd, String newPwd) {
        SysUser userInfo = (SysUser) SecurityUtils.getSubject().getPrincipal();
        if (!oldPwd.equals(userInfo.getPwd())){
            return ResultGenerator.genFailResult(ResultCode.OLD_PASSWORD_ERROR);
        }
        userInfo.setUpdateTime(new Date());
        userInfo.setUpdator(userInfo.getId());
        int count = sysUserMapper.updateByPrimaryKey(userInfo);
        if (count>0){
            return ResultGenerator.genSuccessResult();
        }else{
            return ResultGenerator.genFailResult();
        }
    }
}
